#!/usr/bin/python2.7
"Decodes dyreza resources from the original Exe"
__AUTHOR__ = 'hasherezade'

import argparse

def decode(data, key_data):
    decoded = bytearray()
    i = 0
    for i in range(0, len(data)):
        val_index = data[i]
        if val_index >= len(key_data):
            print "Invalid key data!"
            return ""
        decoded.append(key_data[val_index])
    return decoded

def find_pe(data):
    while len(data):
        mz_start = data.find('MZ')
        if mz_start == -1:
            return None
        pe_start = data[mz_start:]
        data = data[mz_start + len('MZ'):]
        pe = data.find('PE')
        if pe != -1:
            return pe_start
    return None

def dump_to_file(filename, data):
    with open(filename, 'w') as f:
        f.write(data)

def main():
    parser = argparse.ArgumentParser(description="Dyreza payload decoder")
    parser.add_argument('--datafile',dest="datafile",default=None,help="File with data", required=True)
    parser.add_argument('--keyfile',dest="keyfile",default=None, help="File with key", required=True)
    parser.add_argument('--dllname',dest="dllname",default="DyrezaInner.dll", help="Where to dump the DLL", required=False)
    parser.add_argument('--outfile',dest="outfile",default="out.bin", help="Where to dump the output", required=True)
    args = parser.parse_args()

    data = bytearray(open(args.datafile, 'rb').read())
    if len(data) == 0x100: #file with key
        print "---\nThe file: '%s'\ncontains key. Use it as: --keyfile\n---" % (args.datafile)
        return
        
    key_data = bytearray(open(args.keyfile, 'rb').read())
    decoded = decode(data, key_data)
    dump_to_file(args.outfile, decoded)
    print "Dumped decoded to: %s" % (args.outfile)

    dll_data = find_dll(decoded)
    if dll_data is None:
        return

    dump_to_file(args.dllname, dll_data)
    print "Extracted DLL to: %s" % (args.dllname)

if __name__ == '__main__':
    main()
